from waveapi import events
from waveapi import model
from waveapi import robot
import re
import logging
from MetroNorthDao import MetroNorthDao

ROBOT_NAME = 'metro-north-bot'
PATTERN_OBJECT = re.compile('TRAIN:\s*(\S+),\s*(\S+),\s*(\S+),\s*(\S+),\s*(\S+)')
DAO = MetroNorthDao()

def HandleBlip(blip, context):
    cmd = blip.GetDocument().GetText().upper();
    logging.debug("Have new blip: #%s#" % cmd)

    matchGroups = PATTERN_OBJECT.match(cmd)
    if matchGroups : 
        start = matchGroups.group(1)
        end = matchGroups.group(2)
        day = matchGroups.group(3)
        time = "%s:00" % matchGroups.group(4)
        am_pm = matchGroups.group(5)       
        
        message = "Requesting: %s,%s,%s %s %s\n" % (start, end, day, time, am_pm)
        
        child = blip.GetDocument().AppendInlineBlip()
        child.GetDocument().SetText(message)
        
        child.GetDocument().AppendText("Depart\tArrive\n")
        
        trains = DAO.getSchedulesByName(start, end, day, time, am_pm) 
        for train in trains:
            child.GetDocument().AppendText("%s\t%s\n" % (train[0],train[1]))      
    

def OnBlipSubmitted(properties, context):
    """Invoked when any blip we are interested in is submitted."""
    blip_id = properties['blipId']
    blip = context.GetBlipById(blip_id)
    HandleBlip(blip, context)

def Setup(properties, context):
    """Called when this robot is first added to the wave."""
    """Invoked when the robot has been added."""
    root_wavelet = context.GetRootWavelet()
    into_blip = root_wavelet.CreateBlip();
    into_blip.GetDocument().SetText("Hi, I can give you details on metro north train schedules.\n")
    into_blip.GetDocument().AppendText("Enter requests in the following form:\n")
    into_blip.GetDocument().AppendText("Train: START, END, Day (MM/DD/YYYY), hour (12), AM|PM\n");
    into_blip.GetDocument().AppendText("Example: Train: DARIEN, STAMFORD, 1/02/2010, 1, PM\n");

if __name__ == '__main__':
    myRobot = robot.Robot(ROBOT_NAME,
        image_url='http://%s.appspot.com/assets/robot.jpg' % ROBOT_NAME,
        version='1',
        profile_url='http://%s.appspot.com/' % ROBOT_NAME)
    myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, Setup)
    myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
    myRobot.RegisterHandler(events.WAVELET_BLIP_CREATED, OnBlipSubmitted)    
    myRobot.Run(debug=True)
